package com.si.anddos;

import java.util.Calendar;

import com.si.anddos.dpadapters.AnddosDbAdapter;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;


/**
 * A class representing New Download activity in anddos application
 * @author Carlos Martinez
 *
 */
public class DownloadNewActivity extends OptionsMenuActivity {
	private static final int TIME_DIALOG_ID = 0;
	private static final int DATE_DIALOG_ID = 1;
	
	private static final int ACTIVITY_CREATE=0;
	
	private boolean wasNewAccountCreated = false;
	
	private EditText editTextUrlNew;
	private Spinner spinnerAccounts;
	private Button buttonNewAccount;
	private Button buttonDownloadCreate;
	private AnddosDbAdapter mDbHelper;
	
    private Button buttonPickDownloadTime;
    private int pickHour;
    private int pickMinute;
    
    private Button buttonPickDownloadDate;
    private int pickDay;
    private int pickYear;
    private int pickMonth;
    
    private CheckBox checkboxDownloadNow;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.download_new); 
        setTitle(R.string.titleNewDownload);
        
        // on click listener for button download (not implemented yet)
        buttonDownloadCreate = (Button) findViewById(R.id.buttonDownloadCreate);
        buttonDownloadCreate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	// check for empty fields
            	if(TextUtils.isEmpty(editTextUrlNew.getText()))
            	{
            		createAlertEmptyUrl();
            	} else if(spinnerAccounts.getSelectedItemId() == AdapterView.INVALID_ROW_ID){
            		createAlertNoAccount();
            	}
            	else
            	{
            		saveDownload();
            		setResult(RESULT_OK);
            		finish();
            	}
            }

			
        });
        
        // on click listener for button new account
        buttonNewAccount = (Button) findViewById(R.id.buttonNewAccount);
        buttonNewAccount.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	// start new account activity for result
                Intent i = new Intent(v.getContext(), AccountNewActivity.class);
                startActivityForResult(i, ACTIVITY_CREATE);
            }
        });
        
        editTextUrlNew = (EditText) findViewById(R.id.editTextUrlNew);
        spinnerAccounts = (Spinner) findViewById(R.id.spinnerAccounts);
        
        //listener for pick time button
        buttonPickDownloadTime = (Button) findViewById(R.id.buttonPickDownloadTime);
        buttonPickDownloadTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });
        
        //listener for pick date button
        buttonPickDownloadDate = (Button) findViewById(R.id.buttonPickDownloadDate);
        buttonPickDownloadDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        //listener for check box download now
        checkboxDownloadNow = (CheckBox) findViewById(R.id.checkboxDownloadNow);
        checkboxDownloadNow.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks, depending on whether it's now checked
                if (((CheckBox) v).isChecked()) {
                   buttonPickDownloadDate.setEnabled(false);
                   buttonPickDownloadTime.setEnabled(false);
                } else {
                	buttonPickDownloadDate.setEnabled(true);
                    buttonPickDownloadTime.setEnabled(true); 
                }
            }
        });
       
        
        // get url from edit text on main screen
        Bundle extras = getIntent().getExtras();
        String url = extras != null ? extras.getString("url") : null;
        if(url != null)
        	editTextUrlNew.setText(url);
        
        // create accounts db adapter
        mDbHelper = new AnddosDbAdapter(this);
        
	}
	
	public void serviceStarted() {
    	Toast.makeText(getBaseContext(), "Service ok", Toast.LENGTH_SHORT).show();
	}
	
	private void populateAccounts()
	{
		mDbHelper.open();
		// Get all of the rows from the database and create the item list
        Cursor accountsCursor = mDbHelper.getAllAccounts();
        startManagingCursor(accountsCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{AnddosDbAdapter.colAccountUsername, AnddosDbAdapter.colAccountService};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.textAccountRow, R.id.textAccountRowService};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter accounts = 
            new SimpleCursorAdapter(this, R.layout.account_list_row, accountsCursor, from, to);

        // disable spinner if no accounts is in database
        if(accounts.getCount()==0)
        	spinnerAccounts.setEnabled(false);
        spinnerAccounts.setAdapter(accounts);
        
        
        if(wasNewAccountCreated)
        {
        	spinnerAccounts.setSelection(spinnerAccounts.getCount()-1);
        	wasNewAccountCreated = false;
        }
        
        mDbHelper.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		//populate accounts from db to spinner
		populateAccounts();
		
		//load default time from settings
		SharedPreferences settings = getSharedPreferences(Globals.PREFS_NAME, 0);
        pickHour = settings.getInt("defHour", 0);
        pickMinute = settings.getInt("defMinute", 0);
        
        int defDate = settings.getInt("date", 0);
        final Calendar c = Calendar.getInstance();
        if(defDate == 1) c.add(Calendar.DAY_OF_YEAR, 1);
        pickYear = c.get(Calendar.YEAR);
        pickMonth = c.get(Calendar.MONTH);
        pickDay = c.get(Calendar.DAY_OF_MONTH);
        // display the loaded time
        updateButtonDownloadTimeDisplay();
        // display the current date 
        updateButtonDownloadDateDisplay();
	}
	
	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
	    new TimePickerDialog.OnTimeSetListener() {
	        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	            pickHour = hourOfDay;
	            pickMinute = minute;
	            updateButtonDownloadTimeDisplay();
	        }
	};
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                pickYear = year;
                pickMonth = monthOfYear;
                pickDay = dayOfMonth;
                updateButtonDownloadDateDisplay();
            }
     };
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// creating time picker dialog
	    switch (id) {
	    case TIME_DIALOG_ID:
	        return new TimePickerDialog(this, mTimeSetListener, pickHour, pickMinute, true);
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this, mDateSetListener, pickYear, pickMonth, pickDay);
	    }
	    return null;
	}
	
	private void updateButtonDownloadTimeDisplay() {
		//updates the time we display as the text in button
		buttonPickDownloadTime.setText(new StringBuilder()
			.append(pad(pickHour))
			.append(":")
			.append(pad(pickMinute)));
	}

	private void updateButtonDownloadDateDisplay() {
		//updates the date we display as the text in button
		buttonPickDownloadDate.setText(
	            new StringBuilder()
	                    // Month is 0 based so add 1
	                    .append(pickMonth + 1).append("-")
	                    .append(pickDay).append("-")
	                    .append(pickYear).append(" "));
	}
	
	private static String pad(int c) {
		// adding zeros for correct time viewing
	    if (c >= 10)
	        return String.valueOf(c);
	    else
	        return "0" + String.valueOf(c);
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	if(resultCode != RESULT_CANCELED)
    		wasNewAccountCreated = true;
    }
	
	private void saveDownload() {
		if(checkboxDownloadNow.isChecked())
		{
	        Calendar c = Calendar.getInstance();
	        pickYear = c.get(Calendar.YEAR);
	        pickMonth = c.get(Calendar.MONTH);
	        pickDay = c.get(Calendar.DAY_OF_MONTH);
	        pickMinute = c.get(Calendar.MINUTE);
	        pickHour = c.get(Calendar.HOUR_OF_DAY);
	       
		}
		
		Time dateTime = new Time();
		dateTime.set(0, pickMinute, pickHour, pickDay, pickMonth, pickYear);
		dateTime.normalize(true);
		String url = editTextUrlNew.getText().toString();
		String[] items = url.split("/");
		String fileName = items[items.length-1];
    	long accountId = spinnerAccounts.getSelectedItemId();
    	
    	mDbHelper.open();
        // save download to database
        long id = mDbHelper.createDownload(dateTime, url, fileName, accountId);
        if (id > 0) {
                // vse ok
        }
        mDbHelper.close();
        
        if (!DownloadProviderService.running) {
        	Intent service = new Intent(this, DownloadProviderService.class);
        	this.startService(service);
        }
    }
    
    private void createAlertEmptyUrl()
    {
    	// create alert dialog if user left empty fields (username or password)
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.alertSaveNewDownloadTitle)
    			.setMessage(R.string.alertSaveNewDownloadMessage)
    			.setCancelable(false)
    			.setNegativeButton(R.string.alertSaveNegButton, new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int id) {
    					dialog.cancel();
    				}
    			});
    	AlertDialog alert = builder.create();
    	alert.show();
    }

    private void createAlertNoAccount() {
    	// create alert dialog if user left empty account field
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.alertSaveNewDownloadTitle)
    			.setMessage(R.string.alertSaveNewDownloadMessage2)
    			.setCancelable(false)
    			.setNegativeButton(R.string.alertSaveNegButton, new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int id) {
    					dialog.cancel();
    				}
    			});
    	AlertDialog alert = builder.create();
    	alert.show();
		
	}
}
